<template>
	<view class="container">
		<view class="address" v-if="address.length">
			<!-- 收货地址项 -->
			<radio-group @change.native.stop="setDefaultAddress" style="width: 100%;">
				<view class="address-item" v-for="item in address" :key="item.id" >
					<view class="item-content" @click.stop.prevent="selAddress(item.id)">
						<view class="user">
							<text class="">{{ item.name }}</text>
							<text class="contact">{{ item.phone }}</text>
						</view>
						<view class="locate">{{ item.province + item.city + item.district }} {{ item.address }}</view>
					</view>
					<view class="item-opa">
						<view class="item-default">

							<radio :value="item.id" :checked="item.useDefault === 1" />
							{{item.useDefault === 1 ?'当前使用' : '使用'}}
						</view>
						<view class="item-edit-area">
							<view class="item-edit">
								<uni-icons type="compose" size="26" color="#b1b1b1"
									@click.native.stop="editAddress(item.id)"></uni-icons>
							</view>
							<view class="item-del">
								<uni-icons type="trash" size="26" color="#b1b1b1" style="margin-left: 20px;"
									@click.native.stop="delAddress(item.id)"></uni-icons>
							</view>
						</view>
					</view>
				</view>
			</radio-group>
		</view>
		<view v-else class="blank">暂无收货地址</view>
		<view class="gaps">

		</view>
		<view class="address-btn-area">
			<button type="primary" @click="addAddress">添加地址</button>
		</view>

		<uni-popup ref="addressPopup" type="center"  :is-mask-click="false">
			<view class="content">
				<uni-forms :rules="rules" :model="form" ref="formRef">
					<!-- 表单内容 -->
					<uni-forms-item name="name" class="form-item">
						<text class="label">收货人</text>
						<input class="input" placeholder="请填写收货人姓名" v-model="form.name" />
					</uni-forms-item>
					<uni-forms-item name="phone" class="form-item">
						<text class="label">手机号码</text>
						<input class="input" placeholder="请填写收货人手机号码" v-model="form.phone" />
					</uni-forms-item>
					<uni-forms-item name="fullLocation" class="form-item">
						<text class="label">所在地区</text>
						<picker class="picker" mode="region" :value="form.fullLocation.split(' ')"
							@change="onRegionChange">
							<view v-if="form.fullLocation">{{ form.fullLocation }}</view>
							<view v-else class="placeholder">请选择省/市/区(县)</view>
						</picker>
						<!-- <view class="map-select" @click="mapSelect">
							<uni-icons type="map" size="26"></uni-icons>
							<view>地图选择</view>
						</view> -->
					</uni-forms-item>
					<uni-forms-item name="address" class="form-item">
						<text class="label">详细地址</text>
						<uni-easyinput type="textarea" autoHeight v-model="form.address" placeholder="街道、楼牌号等信息" />
					</uni-forms-item>
					<uni-forms-item name="useDefault" class="form-item">
						<text class="label">使用</text>
						<switch :checked="form.useDefault === 1" @change="changeDefault" />
					</uni-forms-item>
				</uni-forms>
			</view>
			<view class="btn-area">
				<button type="default" class="button" @click="cancel">取消</button>
				<button type="primary" class="button" @click="onSubmit">保存</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getMyAddress,
		delMyAddress,
		addMyAddress,
		getMyAddressById,
		editMyAddress,
		setDefault
	} from '@/api/consomer/receiveAddressManage/receiveAddressManage.js'
	const chooseLocation = requirePlugin('chooseLocation');
	export default {
		data() {
			return {
				safeBottom: 0,
				address: [],
				eventChannel: undefined,
				form: {
					name: '', // 收货人
					phone: '', // 联系方式
					fullLocation: '陕西省 榆林市 榆阳区', // 省市区(前端展示)
					address: '', // 详细地址
					province: '陕西省',
					city: '榆林市',
					district: '榆阳区',
					useDefault: 1,
				},
				id: '',
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '请输入收货人'
						}],
					},
					phone: {
						rules: [{
								required: true,
								errorMessage: '请输入联系方式'
							},
							{
								pattern: '^1[3-9]\\d{9}$',
								errorMessage: '请输入正确的手机号'
							},
						],
					},
					fullLocation: {
						rules: [{
							required: true,
							errorMessage: '请输入所在地区'
						}],
					},
					address: {
						rules: [{
							required: true,
							errorMessage: '请输入详细地址'
						}],
					},
				}
			}
		},
		onLoad() {
			this.eventChannel = this.getOpenerEventChannel();
			this.init()
		},
		onShow() {
			const location = chooseLocation.getLocation()
			if (location) {
				this.form.province = location.province
				this.form.city = location.city
				this.form.district = location.district
				const fullAddre = location.province + location.city + location.district
				this.form.fullLocation = location.province + ' ' + location.city + ' ' + location.district
				let addr = location.address
				addr = addr.replace(fullAddre, "")
				this.form.address = addr + location.name
			}
		},
		methods: {
			init() {
				uni.getSystemInfoAsync({
					success: (res) => {
						this.safeBottom = res.screenHeight - res.safeArea.bottom
					}
				})
				this.getMyAddressInit()
			},
			getMyAddressInit() {
				getMyAddress().then(res => {
					this.address = res
				})
			},
			addAddress() {
				this.$refs.addressPopup.open();
			},
			cancel() {
				this.$refs.addressPopup.close();
			},
			selAddress(id) {
				this.eventChannel.emit('selAddr', {
					id: id
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 100)
			},
			setDefaultAddress(item) {
				setDefault(item.detail.value).then(res => {
					uni.showToast({
						icon: "none",
						title: '设置成功'
					})
					this.address.forEach(e => {
						if (e.id === item.detail.value) {
							e.useDefault = 1
						} else {
							e.useDefault = 0
						}
					})
					// this.eventChannel.emit('selAddr', {
					// 	id: item.detail.value
					// })
				})
			},
			editAddress(id) {
				this.id = id
				getMyAddressById(id).then((res) => {
					this.form = {
						...res
					}
					this.form.fullLocation = res.province + ' ' + res.city + ' ' + res.district
				})
				this.$refs.addressPopup.open();
			},
			delAddress(id) {
				const _this = this
				uni.showModal({
					title: '确定删除?',
					success: (res) => {
						if (res.confirm) {
							delMyAddress(id).then((rs) => {
								_this.address = _this.address.filter((it) => {
									return it.id !== id
								})
							})
						}
					}
				})
			},
			mapSelect() {
				const key = 'QCOBZ-AZ43A-RURKK-CS55U-4TZ3E-VCFB6'; //使用在腾讯位置服务申请的key
				const referer = '107商圈'; //调用插件的app的名称

				wx.navigateTo({
					url: `plugin://chooseLocation/index?key=${key}&referer=${referer}`
				});
			},
			onRegionChange(ev) {
				this.form.fullLocation = ev.detail.value.join(' ')
				this.form.province = ev.detail.value[0]
				this.form.city = ev.detail.value[1]
				this.form.district = ev.detail.value[2]
				this.form.address = ''
			},
			changeDefault(e) {
				this.form.useDefault = e.detail.value ? 1 : 0
			},
			onSubmit() {
				this.$refs.formRef.validate().then(() => {
					if (this.id) {
						editMyAddress({
							id: this.id,
							bo: this.form
						}).then((res) => {
							uni.showToast({
								icon: "success",
								title: '修改成功'
							})

							this.address = this.address.filter(e => {
								return e.id !== this.id
							})
							this.address.unshift(res)
							if(res.useDefault === 1) {
								this.eventChannel.emit('selAddr', {
									id: res.id
								})
							}

							this.$refs.addressPopup.close();
						})
					} else {
						addMyAddress(this.form).then((res) => {
							uni.showToast({
								icon: "success",
								title: '保存成功'
							})
							this.address.unshift(res)
							if(res.useDefault === 1) {
								this.eventChannel.emit('selAddr', {
									id: res.id
								})
							}
							this.$refs.addressPopup.close();
						})
					}
					
				})
			}
		}
	}
</script>

<style lang="scss">
	.container {
		height: 100vh;
	}

	.address-btn-area {
		button {
			width: 100%;
		}
	}

	.blank {
		text-align: center;
		font-size: 32rpx;
		color: #888;
	}

	/* 删除按钮 */
	.delete-button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 50px;
		height: 100%;
		font-size: 28rpx;
		color: #fff;
		border-radius: 0;
		padding: 0;
		background-color: #cf4444;
	}

	.item-edit-area {
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-items: center;
	}

	.address {
		margin: 0 auto;
		padding: 0 10px;

		.address-item {
			padding: 10px;
			margin-top: 10px;
			border-radius: 10px;
			background-color: #fff;

			.locate {
				font-size: 14px;
				font-weight: 600;
				margin-top: 10px;
			}

			.user {
				font-size: 16px;
				margin-top: 5px;
				font-weight: bold;
			}

			.contact {
				margin-left: 10px;
			}
		}

		.item-opa {
			border-top: 1px solid #b1b1b1;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			width: 100%;
			align-items: center;
			margin-top: 10px;
			padding-top: 10px;


		}
	}

	.content {
		margin: 20rpx 20rpx 0;
		padding: 0 20rpx;
		border-radius: 10rpx;
		background-color: #fff;
		width: 650rpx;

		.form-item,
		.uni-forms-item {
			display: flex;
			align-items: center;
			min-height: 96rpx;
			padding: 25rpx 10rpx 40rpx;
			background-color: #fff;
			font-size: 28rpx;
			border-bottom: 1rpx solid #ddd;
			position: relative;
			margin-bottom: 0;

			// 调整 uni-forms 样式
			.uni-forms-item__content {
				display: flex;
			}

			.uni-forms-item__error {
				margin-left: 150rpx;
			}

			&:last-child {
				border: none;
			}

			.label {
				width: 150rpx;
				color: #333;
			}

			.input {
				flex: 1;
				display: block;
				height: 46rpx;
			}

			.switch {
				position: absolute;
				right: -20rpx;
				transform: scale(0.8);
			}

			.picker {
				flex: 1;
			}

			.placeholder {
				color: #808080;
			}
		}
	}

	.map-select {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		border-left: 1px solid #b1b1b1;
		align-items: center;
	}

	.button {
		height: 80rpx;
		margin: 30rpx 20rpx;
		color: #fff;
		border-radius: 80rpx;
		font-size: 30rpx;
		background-color: $base-color;
		flex: 1;
	}

	.btn-area {
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-content: center;
	}
</style>